package com.mes.service.impl;

import com.google.code.kaptcha.Constants;
import com.mes.constant.MesConstants;
import com.mes.constant.ResponseStatus;
import com.mes.mapper.PrivilegeMapper;
import com.mes.mapper.RolePrivilegeMapper;
import com.mes.mapper.UserMapper;
import com.mes.mapper.UserRoleMapper;
import com.mes.po.*;
import com.mes.service.ILoginService;
import com.mes.util.MesResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
@SessionAttributes(Constants.KAPTCHA_SESSION_KEY)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePrivilegeMapper rolePrivilegeMapper;

    @Autowired
    private PrivilegeMapper privilegeMapper;
    @Override
    public MesResponse login(Integer userNum, String passWord,String code) {
        MesResponse response = new MesResponse();
        response.setStatus(ResponseStatus.FAILED);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        if(null != code){
            // 获取session中的验证码
            String sessionCode = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            // 如果输入的验证码和会话的验证码不一致的,提示用户输入有误
            if(null != sessionCode && !code.equalsIgnoreCase(sessionCode)){
                response.setMessage("验证码错误！");
                return response;
            }
        }
        User user = userMapper.selectByUserNum(userNum);
        if (null == user) {
            response.setMessage("该用户不存在！");
        } else if (!passWord.equals(user.getPassword())) {
            response.setMessage("密码输入错误！");
        }else if(1 != user.getUserStatus()){
            response.setMessage("用户状态不正常！");
        }
        response.setStatus(ResponseStatus.SUCESS);
        response.setMessage("登录成功！");
        request.getSession().setAttribute(MesConstants.userId,user.getUserId());
        return response;
    }
}
